<?php
echo <<<_END

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js map-page"> <!--<![endif]-->

<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Photogrammar: Map</title>
    <link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
    <link rel="stylesheet" type="text/css" href="../css/styleMain.css"/>
    <link rel="stylesheet" href="../css/leaflet.css" />
    <!--[if lte IE 8]><link rel="stylesheet" href="http://code.leafletjs.com/leaflet-0.3.1/leaflet.ie.css" /><![endif]-->
    <link  href="../css/cartodb-leaflet.css" rel="stylesheet" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script src="../js/leaflet.js"></script>
    <script type="text/javascript" src="../js/wax.leaf.min.js"></script>
    <script type="text/javascript" src="../dist/cartodb-leaflet.js"></script>
    <script type="text/javascript" src="../dist/cartodb-popup-min.js"></script>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(function() 
        {
                $('#map') .css({'height': (($(window).height()) - 104)+'px'});
            
                $(window).bind('resize', function(){
                    $('#map') .css({'height': (($(window).height()) - 104)+'px'});
                });
        });

    </script>

    <script type="text/javascript">
        	var county, map;
        function initialize() {
          map = new L.Map('map').setView(new L.LatLng(39.8, -98.2), 4);
_END;


    // PHP Intialized
    function get_post($var)
    {
        return $_GET[$var];
    }

    $year_start = get_post('year_start');
    $year_end = get_post('year_end');
    $month_start = get_post('month_start');
    $month_end = get_post('month_end');
    $pname = get_post('pname');
    $shape = get_post('shape');

    if($year_start == "") $year_start = 1935;
    if($year_end == "") $year_end = 1945;
    if($month_start == "") $month_start = 1;
    if($month_end == "") $month_end = 12;
    if($pname == "") $pname = "All";
    if($shape != "point") $shape = "box";

    // Function from anyexample to convert rgb to hex color for chloropleth
    function rgb2html($r, $g=-1, $b=-1)
    {
        if (is_array($r) && sizeof($r) == 3)
            list($r, $g, $b) = $r;

        $r = intval($r); $g = intval($g);
        $b = intval($b);

        $r = dechex($r<0?0:($r>255?255:$r));
        $g = dechex($g<0?0:($g>255?255:$g));
        $b = dechex($b<0?0:($b>255?255:$b));

        $color = (strlen($r) < 2?'0':'').$r;
        $color .= (strlen($g) < 2?'0':'').$g;
        $color .= (strlen($b) < 2?'0':'').$b;
        return '#'.$color;
    }

if($shape == "box") {

echo <<<_END

          mapboxUrl = 'http://{s}.tiles.mapbox.com/v3/mapbox.world-blank-light/{z}/{x}/{y}.png';
          mapbox = new L.TileLayer(mapboxUrl, {maxZoom: 18, attribution: ""});
          map.addLayer(mapbox,true);

    var style = "#uscounties{line-color:#3b3b3b;line-opacity:1;line-width:1;polygon-opacity:0.8;}#uscounties[npics>200]{polygon-fill:#00250f;}#uscounties[npics<=200]{polygon-fill:#005824;}#uscounties[npics<=100]{polygon-fill:#238B45;}#uscounties[npics<=50]{polygon-fill:#41AE76;}#uscounties[npics<=25]{polygon-fill:#66C2A4;}#uscounties[npics<=14]{polygon-fill:#CCECE6;}#uscounties[npics<=7]{polygon-fill:#D7FAF4;}#uscounties[npics<=3]{polygon-fill:#EDF8FB;}";
    var query = "SELECT uscounties.cartodb_id,uscounties.name,uscounties.state_name,ST_SIMPLIFY(uscounties.the_geom_webmercator,0.0001) as the_geom_webmercator,ST_ASGEOJSON(ST_SIMPLIFY(uscounties.the_geom,0.0001)) as geometry,COUNT(*) as npics  FROM uscounties,fsadata WHERE uscounties.fips = fsadata.fips GROUP BY uscounties.cartodb_id";

    // Create a CartoDB leaflet popup
      var popup = new L.CartoDBPopup();
        // Initialize hover polygon
      var polygon = new L.GeoJSON(null);
        // Hover polygon style
      var polygon_style = {color: "#FFCC00", weight: 3, opacity:1, fillOpacity: 0, fillColor:"#FFCC00", clickable:false};
        // Create the CartoDB layer
      county = new L.CartoDBLayer({
            map: map,
            user_name:"statmath",
            table_name: 'uscounties',
            query: query,
            tile_style: style,
            opacity: 1,
            interactivity: "cartodb_id, geometry,name,state_name,npics",  

            featureOver: function(ev,latlng,pos,data) {
                document.body.style.cursor = "pointer";
                
                // Show the hover polygon if it is a different feature
                if (data.cartodb_id != polygon.cartodb_id) {
                  map.removeLayer(polygon);
                
                  polygon = new L.GeoJSON(JSON.parse(data.geometry), {
                    style: function (feature) {
                      return polygon_style;
                    }
                  }).addTo(map);;
                  polygon.cartodb_id = data.cartodb_id;
                }
            },
            featureOut: function() {
                document.body.style.cursor = "default";
                
                // Hide and remove in any case the hover polygon
                polygon.cartodb_id = null;
                polygon.off("featureparse");
                map.removeLayer(polygon)
            },
            featureClick: function(ev,latlng,pos,data) {
              ev.stopPropagation();
              // Set popup content
              var stateNameBox = data["state_name"];
              var stateNameUrlBox = stateNameBox.replace(" ","+"); 
              var countyNameBox = data["name"];
              var countyNameUrlBox = countyNameBox.replace(" ","+"); 
_END;

    // Construct pop-up content based on map search results
    echo "popup.setContent(stateNameBox + '<div id=\"map-popup-county\">' + countyNameBox + '</div><div id=\"map-popup-link\"><a href=\"http://photogrammar.yale.edu/search/results.php?start=0&search=&pname=";
    if($pname != "All") echo $pname;
    echo "&lot=&van=&state=' + stateNameUrlBox + '&county=' + countyNameUrlBox +'&city=&year_start=";
    echo $year_start;
    echo "&month_start=";
    echo $month_start;
    echo "&year_stop=";
    echo $year_end;
    echo "&month_stop=";
    echo $month_end;
    echo "\">' + 'See ' + data[\"npics\"] + ' Photos</a></div>')";

echo <<<_END
              // Set latlng
              popup.setLatLng(latlng);

              // Show it!
              map.openPopup(popup);
            },
            auto_bound: false,
            debug: false
          });
          map.addLayer(county);
        }

        function changeLayer(year_start, month_start, year_end, month_end, pname) {
              var dstart = year_start + (month_start-1)/12;
              var dend = year_end + (month_end-1)/12;
              if(pname == "All") {
                  qry = "SELECT uscounties.cartodb_id,uscounties.name,uscounties.state_name,ST_SIMPLIFY(uscounties.the_geom_webmercator,0.0001) as the_geom_webmercator,ST_ASGEOJSON(ST_SIMPLIFY(uscounties.the_geom,0.0001)) as geometry,COUNT(*) as npics  FROM uscounties,fsadata WHERE uscounties.fips = fsadata.fips AND fsadata.year + (fsadata.month-1)/12 >=" + dstart + " AND fsadata.year + (fsadata.month-1)/12 <= " + dend + "  GROUP BY uscounties.cartodb_id";
                } else {
                  qry = "SELECT uscounties.cartodb_id,uscounties.name,uscounties.state_name,ST_SIMPLIFY(uscounties.the_geom_webmercator,0.0001) as the_geom_webmercator,ST_ASGEOJSON(ST_SIMPLIFY(uscounties.the_geom,0.0001)) as geometry,COUNT(*) as npics  FROM uscounties,fsadata WHERE uscounties.fips = fsadata.fips AND fsadata.year + (fsadata.month-1)/12 >=" + dstart + " AND fsadata.year + (fsadata.month-1)/12 <= " + dend + " AND pname ='" + pname + "' GROUP BY uscounties.cartodb_id";
                }
              county.setQuery(qry);
          }


    </script>

_END;
}

if($shape == "point") {
echo <<<_END
		  mapboxUrl = 'http://{s}.tiles.mapbox.com/v3/mapbox.world-blank-light/{z}/{x}/{y}.png'
/*           mapboxUrl = 'http://{s}.tiles.mapbox.com/v3/cartodb.map-1nh578vv/{z}/{x}/{y}.png'; */
          mapbox = new L.TileLayer(mapboxUrl, {maxZoom: 18, attribution: ""});
          map.addLayer(mapbox,true);

          // Create a CartoDB popup
          var popup = new L.CartoDBPopup();
          var hover_style = {radius:5, color:"#333", weight:1, opacity:1, fillColor: "#FFCC00", fillOpacity:1, clickable:true};
          var circleMarker = {};
          var query = "SELECT the_geom,the_geom_webmercator,city AS mapcity,state,city,county,count(*) AS npics, ST_X(the_geom) AS lng,ST_Y(the_geom) AS lat FROM {{table_name}} WHERE city!='NA' GROUP BY the_geom,the_geom_webmercator,state,county,city";

          // Now the CartoDB layer, the photographs
          earthquakes = new L.CartoDBLayer({
            map: map,
            user_name:"statmath",
            table_name: 'fsadata',
            query: query,
            tile_style: "#{{table_name}}{marker-opacity:0.5; marker-fill:#006BB4; marker-allow-overlap:true; marker-width:6; marker-height:6}",
            interactivity: "state,county,npics,city,lng,lat",
            featureOver: function(ev,latlng,pos,data) {
              document.body.style.cursor = "pointer";

                if (data.county != circleMarker.county) {
                  map.removeLayer(circleMarker);
                
                  circleMarker = new L.CircleMarker(new L.LatLng(data.lat, data.lng), hover_style);
                  circleMarker.county = data.county;
                  
                  map.addLayer(circleMarker);
                }

            },
            featureOut: function() {
              document.body.style.cursor = "default";

                // Hide and remove in any case the hover point
                circleMarker.county = null;
                map.removeLayer(circleMarker)

            },
            featureClick: function(ev,latlng,pos,data) {
              ev.stopPropagation();
              // Set popup content
              var stateName = data["state"];
              var stateNameUrl = stateName.replace(" ","+"); 
              var countyName = data["county"];
              var countyNameUrl = countyName.replace(" ","+"); 
              var cityName = data["city"];
              if(cityName == "NA") cityName = "";
              var cityNameUrl = cityName.replace(" ","+"); 

_END;

    // Construct pop-up content based on map search results
    echo "popup.setContent(stateName + '<div id=\"map-popup-county\">' + countyName + '</div><div id=\"map-popup-city\">' + cityName + '</div><div id=\"map-popup-link\"><a href=\"http://photogrammar.yale.edu/search/results.php?start=0&search=&pname=";
    if($pname != "All") echo $pname;
    echo "&lot=&van=&state=' + stateNameUrl + '&county=' + countyNameUrl +'&city=' + cityNameUrl + '&year_start=";
    echo $year_start;
    echo "&month_start=";
    echo $month_start;
    echo "&year_stop=";
    echo $year_end;
    echo "&month_stop=";
    echo $month_end;
    echo "\">' + 'See ' + data[\"npics\"] + ' Photos</a></div>')";

echo <<<_END
              // Set latlng
              popup.setLatLng(latlng);

              // Show it!
              map.openPopup(popup);
            },
            auto_bound: false,
            debug: false
          });
          // Adding layer to map
          map.addLayer(earthquakes);
        }

        function changeLayer(year_start, month_start, year_end, month_end, pname) {
              var dstart = year_start + (month_start-1)/12;
              var dend = year_end + (month_end-1)/12;
              if(pname == "All") {
                  qry = "SELECT the_geom,the_geom_webmercator,state,city,county,count(county) AS npics, ST_X(the_geom) AS lng,ST_Y(the_geom) AS lat FROM {{table_name}} WHERE year + (month-1)/12 >=" + dstart + " AND year + (month-1)/12 <= " + dend + " GROUP BY the_geom,the_geom_webmercator,state,city,county";
                } else {
                  qry = "SELECT the_geom,the_geom_webmercator,state,city,county,count(county) AS npics, ST_X(the_geom) AS lng,ST_Y(the_geom) AS lat FROM {{table_name}} WHERE year + (month-1)/12 >=" + dstart + " AND year + (month-1)/12 <= " + dend + " AND pname ='" + pname + "' GROUP BY the_geom,the_geom_webmercator,state,city,county";
                }
              earthquakes.setQuery(qry);
          }


    </script>
_END;
}

    echo '</head>';
    echo '<body onload="initialize(); changeLayer(' . $year_start . ',' . $month_start . ',' . $year_end . ',' . $month_end . ",'" . $pname . "'" . ')">';

echo <<<_END
<div id="header">
	<div id="logo">
    	<h1><a href="/"><img src="/images/photogrammar-wordmark.jpg" alt="Yale Photogrammar" title="Yale Photogrammar" /></a></h1>
    </div><!-- /#logo -->
    <nav id="menu" class="menu">
        <ul>
          <li class="single-link">
            <a href="/index.php">Home</a>
            </li>
          <li class="current">
            <a href="/map/">Map</a>
            </li>
          <li class="single-link"><!-- Using class="single-link" for links with no dropdown -->
            <a href="/browse/">Browse</a>
            </li>
          <li class="single-link"><!-- Using class="single-link" for links with no dropdown -->
            <a href="/search/">Search</a>
            </li>
          <li class="single-link"><!-- Using class="single-link" for links with no dropdown -->
            <a href="/about/">About</a>
            </li>
          <li class="single-link"><!-- Using class="single-link" for links with no dropdown -->
            <a href="/blog/">Blog</a>
            </li>
        </ul>
    </nav><!-- /#menu -->
</div><!-- /#header -->

<div id="map-search-bar">
	<form name="map-search" action='index.php' method="get">
	<div id="map-photographer">
    	<!--<h3>Photographer</h3><input style="width: 150px;color:#808080;" type="text" name="photographer-name" onfocus="if (this.value==this.defaultValue) this.value = ''" onblur="if (this.value=='') this.value = this.defaultValue" value="ex. vaschon, lange"/> -->
_END;

        echo '<h3>Photographer</h3><select name="pname">';

        $pnom = array('1'=>'Alfred T. Palmer', '2'=>'Arthur Rothstein', '3'=>'Arthur S. Siegel', '4'=>'Ben Shahn', '5'=>'Carl Mydans', '6'=>'Dorothea Lange', '7'=>'Esther Bubley', '8'=>'Gordon Parks', '9'=>'Howard R. Hollem', '10'=>'Jack Delano', '11'=>'John Collier', '12'=>'John Vachon', '13'=>'Marion Post Wolcott', '14'=>'Marjory Collins', '15'=>'Russell Lee', '0'=>'All');

        
        for($j = 0; $j <= 15; ++$j) {
            echo '<option ';
            if ($pname == $pnom[$j]) echo 'selected="true"';
            echo 'value="' . $pnom[$j] . '">' . $pnom[$j] . '</option>';            
        }

        echo '</select>';

echo <<<_END
    </div>
<!-- /#map-photographer -->
    <div id="map-from-date">
    	<h3>From</h3>
_END;


$mons = array('1'=>'January ', '2'=>'February ', '3'=>'March ', '4'=>'April ', '5'=>'May ', '6'=>'June ', '7'=>'July ', '8'=>'August ',
                 '9'=>'September ', '10'=>'October ', '11'=>'November ', '12'=>'December ', '0'=>'');

        // Month Start Values
        echo '<select name="month_start">';
        for($j = 1; $j <= 12; ++$j) {
            echo '<option ';
            if ($month_start == $j) echo 'selected="true"';
            echo 'value="' . $j . '">' . $mons[$j] . '</option>';            
        }
        echo '</select>';

        // Year Start Values
        echo '<select name="year_start">';
        for($j = 1935; $j <= 1945; ++$j) {
            echo '<option ';
            if ($year_start == $j) echo 'selected="true"';
            echo 'value="' . $j . '">' . $j . '</option>';            
        }
        echo '</select>';

        echo '</div><!-- /#map-from-date -->';
        echo '<div id="map-to-date">';
        echo '<h3>To</h3>';
        echo '';

        // Month End Values
        echo '<select name="month_end">';
        for($j = 1; $j <= 12; ++$j) {
            echo '<option ';
            if ($month_end == $j) echo 'selected="true"';
            echo 'value="' . $j . '">' . $mons[$j] . '</option>';            
        }
        echo '</select>';

        // Year End Values
        echo '<select name="year_end">';
        for($j = 1935; $j <= 1945; ++$j) {
            echo '<option ';
            if ($year_end == $j) echo 'selected="true"';
            echo 'value="' . $j . '">' . $j . '</option>';            
        }
        echo '</select>';

echo <<<_END
    </div><!-- /#map-to-date -->
    <div id="map-subject">
    	<!--<h3>Subject</h3>
        <select name="map-subject-level-1">
            	<option value="All">All</option>
            	<option value="land">The Land</option>
            <option value="cities-and-towns">Cities and Towns</option>
            <option value="people">People</option>
            <option value="hames-and-living">Homes and Living</option>
            <option value="transportation">Transportation</option>
            <option value="work">Work</option>
            <option value="organized-society">Organized Society</option>
            <option value="war">War</option>
            <option value="medicine-and-health">Medicine and Health</option>
            <option value="religion">Religion</option>
            <option value="intellectual-and-creative-activity">Intellectual and Creative Activity</option>
            <option value="social-and-personal-activity">Social and Personal Activity</option>
        </select> -->
        <!--<select name="map-subject-level-2">
        	<option value="land">The Land</option>
            <option value="cities-and-towns">Cities and Towns</option>
            <option value="people">People</option>
            <option value="hames-and-living">Homes and Living</option>
            <option value="transportation">Transportation</option>
            <option value="work">Work</option>
            <option value="organized-society">Organized Society</option>
            <option value="war">War</option>
            <option value="medicine-and-health">Medicine and Health</option>
            <option value="religion">Religion</option>
            <option value="intellectual-and-creative-activity">Intellectual and Creative Activity</option>
            <option value="social-and-personal-activity">Social and Personal Activity</option>
        </select>
        <select name="map-subject-level-3">
        	<option value="land">The Land</option>
            <option value="cities-and-towns">Cities and Towns</option>
            <option value="people">People</option>
            <option value="hames-and-living">Homes and Living</option>
            <option value="transportation">Transportation</option>
            <option value="work">Work</option>
            <option value="organized-society">Organized Society</option>
            <option value="war">War</option>
            <option value="medicine-and-health">Medicine and Health</option>
            <option value="religion">Religion</option>
            <option value="intellectual-and-creative-activity">Intellectual and Creative Activity</option>
            <option value="social-and-personal-activity">Social and Personal Activity</option>
        </select> -->
    </div><!-- /#map-subject -->
    <div id="map-search">
    <!-- 	<h3>Search</h3><input style="width: 150px;color:#808080;" type="text" name="map-keyword" onfocus="if (this.value==this.defaultValue) this.value = ''" onblur="if (this.value=='') this.value = this.defaultValue" value="enter search terms"/> -->
    </div><!-- /#map-search -->
    <div id="map-subject">
 	<h3>Style</h3>
        <select name="shape">
_END;

    if($shape != "point") {
        echo '<option value="box" selected="true">County boxes</option>';
        echo '<option value="point">Points</option>';
    }
    if($shape == "point") {
        echo '<option value="box">County boxes</option>';
        echo '<option value="point" selected="true">Points</option>';
    }

echo <<<_END
        </select>
    </div><!-- /#map-search -->
	<button type='submit' value='Search'/>Search</button>
    </form>
</div>


<div id="map"></div>

</body>
</html>
_END;

?>
